package myself.study.network.udp.examples.chatroom;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class SendRunnable implements Runnable {
	
	private DatagramSocket clientSocket ;

	public SendRunnable(DatagramSocket clientSocket) {
		this.clientSocket = clientSocket ;
	}

	@Override
	public void run() {
		try {
			//封装键盘录入数据
			BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)) ;
			String line = null ;
			while((line = reader.readLine()) != null) {
				//当键盘输入'886'时，结束客户端请求
				if("886".equals(line)) {
					break ;
				}
				//创建发送数据包
				byte[] buf = line.getBytes() ;
				DatagramPacket packet = new DatagramPacket(buf, 
						buf.length, 
						InetAddress.getByName("127.0.0.1"), 
						10086) ;
				//发送数据包
				clientSocket.send(packet) ;
			}
		} catch (IOException e) {
			e.printStackTrace() ;
		} finally {
			//释放资源
			clientSocket.close() ;
		}
	}

}
